package com.dmx.cep.action.attributeManage;


import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;

import com.dmx.cep.entity.ConfBlock;
import com.dmx.cep.entity.ConfBlockUpdate;
import com.dmx.cep.service.ConfBlockService;
import com.dmx.cep.util.EncodingDetecter;
import com.dmx.fw.constant.ViewConstant;
import com.dmx.fw.web.struts2.action.CommonQueryAction;


/**
 *
 * @author Alex.lu
 *
 */
@SuppressWarnings("serial")
public class ConfBlockAction extends CommonQueryAction {

    private static final String BATCH_DELETE = "batchDelete";
	private ConfBlockService confBlockService;
	private ConfBlock confBlock;

	private Integer[] ids;
	private Integer id;

    private String q_blackorwhite;


    private String q_blockid;


    private String q_blocktype;


    private String q_flag;


    private String q_value;

    private File file;

	// actions begin

	public String execute() throws Exception {
		super.busiId = "confBlockSearch";
		if (ViewConstant.QUERY.equals(super.act)) {
			doQuery();
		} else if (ViewConstant.REQUERY.equals(super.act)) {
			doReQuery();
		} else if (ViewConstant.DELETE.equals(super.act)) {
			this.doDelete();
		} else if (BATCH_DELETE.equals(super.act)) {
			doBatchDelete();
		} else if (ViewConstant.ADDINPUT.equals(super.act)) {
			this.pageState = ViewConstant.ADDSTATUS;
			return doAddInput();
		} else if (ViewConstant.ADDSUBMIT.equals(super.act)) {
			return doAddSubmit();
		} else if (ViewConstant.EDITINPUT.equals(super.act)) {
			this.pageState = ViewConstant.EDITSTATUS;
			return doEditInput();
		} else if (ViewConstant.EDITSUBMIT.equals(super.act)) {
			return doEditSubmit();
		}else if("preImport".equals(this.act)){
			return preImport();
		}else if("doImport".equals(this.act)){
			return doImport();
		}else if("doExport".equals(this.act)){
			return doExport();
		}else {
			super.execute();
		}
		return SUCCESS;
	}

	public String doAddInput() {
		this.pageState = ViewConstant.ADDSTATUS;
		return ViewConstant.ADDINPUT;
	}

	public String doAddSubmit() throws Exception {

//		if (haserrors) {
//			this.setErrorInfo(getText("m3p.asset.distribution.policy.expression.warning"));
//			return ViewConstant.ADDINPUT;
//		}

        /**do your add logics**/

		confBlockService.saveOrUpdateConfBlock(confBlock);
		
		if(confBlock.getBlocktype()==1&&confBlock.getBlackorwhite()==1){
			//关键字、白名单过滤
			ConfBlockUpdate confUpdate=(ConfBlockUpdate)confBlockService.getObject(ConfBlockUpdate.class, "key-white");
			if(confUpdate!=null){
				confUpdate.setUpdateTime(new Date());
				confBlockService.saveObject(confUpdate);				
			}
		}
		if(confBlock.getBlocktype()==1&&confBlock.getBlackorwhite()==0){
			//关键字、黑名单过滤
			ConfBlockUpdate confUpdate=(ConfBlockUpdate)confBlockService.getObject(ConfBlockUpdate.class, "key-black");
			if(confUpdate!=null){
				confUpdate.setUpdateTime(new Date());
				confBlockService.saveObject(confUpdate);				
			}
		}
		if(confBlock.getBlocktype()==0&&confBlock.getBlackorwhite()==1){
			//域名、白名单过滤
			ConfBlockUpdate confUpdate=(ConfBlockUpdate)confBlockService.getObject(ConfBlockUpdate.class, "domain-white");
			if(confUpdate!=null){
				confUpdate.setUpdateTime(new Date());
				confBlockService.saveObject(confUpdate);				
			}
		}
		if(confBlock.getBlocktype()==0&&confBlock.getBlackorwhite()==0){
			//域名、黑名单过滤
			ConfBlockUpdate confUpdate=(ConfBlockUpdate)confBlockService.getObject(ConfBlockUpdate.class, "domain-black");
			if(confUpdate!=null){
				confUpdate.setUpdateTime(new Date());
				confBlockService.saveObject(confUpdate);				
			}
		}
		
		setSuccessinfo(getText("info.addSuccess"));
		super.doReQuery();
		return SUCCESS;
	}

	public String doEditInput() {
		if (this.id != null) {
			this.pageState = "edit";
			confBlock = confBlockService.findConfBlockById(id);

		}
		return ViewConstant.ADDINPUT;
	}

	public String doEditSubmit() throws Exception {


//		if (someerrorcondition) {
//			super.setErrorInfo(getText("m3p.asset.distribution.policy.required.warning"));
//			this.pageState = "edit";
//			return ViewConstant.ADDINPUT;
//		}
        /**do your update logics**/

		confBlockService.saveOrUpdateConfBlock(confBlock);
		
		if(confBlock.getBlocktype()==1&&confBlock.getBlackorwhite()==1){
			//关键字、白名单过滤
			ConfBlockUpdate confUpdate=(ConfBlockUpdate)confBlockService.getObject(ConfBlockUpdate.class, "key-white");
			if(confUpdate!=null){
				confUpdate.setUpdateTime(new Date());
				confBlockService.saveObject(confUpdate);				
			}
		}
		if(confBlock.getBlocktype()==1&&confBlock.getBlackorwhite()==0){
			//关键字、黑名单过滤
			ConfBlockUpdate confUpdate=(ConfBlockUpdate)confBlockService.getObject(ConfBlockUpdate.class, "key-black");
			if(confUpdate!=null){
				confUpdate.setUpdateTime(new Date());
				confBlockService.saveObject(confUpdate);				
			}
		}
		if(confBlock.getBlocktype()==0&&confBlock.getBlackorwhite()==1){
			//域名、白名单过滤
			ConfBlockUpdate confUpdate=(ConfBlockUpdate)confBlockService.getObject(ConfBlockUpdate.class, "domain-white");
			if(confUpdate!=null){
				confUpdate.setUpdateTime(new Date());
				confBlockService.saveObject(confUpdate);				
			}
		}
		if(confBlock.getBlocktype()==0&&confBlock.getBlackorwhite()==0){
			//域名、黑名单过滤
			ConfBlockUpdate confUpdate=(ConfBlockUpdate)confBlockService.getObject(ConfBlockUpdate.class, "domain-black");
			if(confUpdate!=null){
				confUpdate.setUpdateTime(new Date());
				confBlockService.saveObject(confUpdate);				
			}
		}		
		
		setSuccessinfo(getText("info.addSuccess"));
		super.doReQuery();
		return SUCCESS;
	}

	public String doBatchDelete() throws Exception {
		confBlockService.batchDeleteConfBlockByIds(ids);
		setSuccessinfo(getText("info.deleteSuccess"));
		return super.doQuery();
	}


	public String doDelete() throws Exception {
		confBlockService.deleteConfBlockById(id);
		return super.doQuery();
	}

	public String preImport() throws Exception {
		
		return "import";
	}
	
	public String doImport() throws Exception {
		try{
			List<String> lines = new ArrayList<String>(0);

			EncodingDetecter ed = new EncodingDetecter();
			String encodeType = ed.preParse(file.getPath(), null);
			log.info("The import file encoding: " + encodeType);

			if (encodeType != null) {
				if ("UTF-8".equalsIgnoreCase(encodeType)
						|| "ASCII".equalsIgnoreCase(encodeType)) {
					lines = IOUtils.readLines(new FileInputStream(file),
							"UTF-8");

				} else if ("windows-1252".equalsIgnoreCase(encodeType)) {
					lines = IOUtils.readLines(new FileInputStream(file),
							"Unicode");

				} else {
					lines = IOUtils.readLines(new FileInputStream(file),
							encodeType);
				}
			}

			boolean isKeyWhite=false;
			boolean isKeyBlack=false;
			boolean isDomainWhite=false;
			boolean isDomainBlack=false;
			
			List<String[]> result = new ArrayList<String[]>(0);
			for (int i = 0; i < lines.size(); i++) {
				String line = lines.get(i);
				if (line.trim().equals(""))
					continue;

				String[] aLine = line.split(",");
				String[] aLine2=new String[4];

				if (aLine.length < 4) {
					// 格式错误
					this.setErrorInfo(this.getText("file.format.error")+this.getText("error.line")+(i+1));
					return preImport();
				}
			
				if (!(aLine[0].trim().equals("key") || aLine[0].trim().equals(
						"domain"))) {
					// 格式错误
					this.setErrorInfo(this.getText("file.format.error")+this.getText("error.line")+(i+1));
					return preImport();
				}
				aLine2[0] = aLine[0].trim().equals("key") ? "1" : "0";

				if (!(aLine[1].trim().equals("white") || aLine[1].trim()
						.equals("black"))) {
					// 格式错误
					this.setErrorInfo(this.getText("file.format.error")+this.getText("error.line")+(i+1));
					return preImport();
				}
				aLine2[1] = aLine[1].trim().equals("white") ? "1" : "0";

				if (!(aLine[2].trim().equals("0") || aLine[2].trim()
						.equals("1"))) {
					// 格式错误
					this.setErrorInfo(this.getText("file.format.error")+this.getText("error.line")+(i+1));
					return preImport();
				}
				
				int index=line.indexOf(aLine[2]);
				
				
				aLine2[2]=aLine[2].trim();
				
				aLine2[3]=line.substring(index+aLine[2].length()+1);
				
				result.add(aLine2);

				if(isKeyWhite==false&&aLine[0].trim().equals("key")&&aLine[1].trim().equals("white")){
					isKeyWhite=true;
				}
				if(isKeyBlack==false&&aLine[0].trim().equals("key")&&aLine[1].trim().equals("black")){
					isKeyBlack=true;
				}
				if(isDomainWhite==false&&aLine[0].trim().equals("domain")&&aLine[1].trim().equals("white")){
					isDomainWhite=true;
				}	
				if(isDomainBlack==false&&aLine[0].trim().equals("domain")&&aLine[1].trim().equals("black")){
					isDomainBlack=true;
				}				
			}

			confBlockService.saveBlackWhiteList(result);
			
			if(isKeyWhite){
				//关键字、白名单过滤
				ConfBlockUpdate confUpdate=(ConfBlockUpdate)confBlockService.getObject(ConfBlockUpdate.class, "key-white");
				if(confUpdate!=null){
					confUpdate.setUpdateTime(new Date());
					confBlockService.saveObject(confUpdate);				
				}
			}
			if(isKeyBlack){
				//关键字、黑名单过滤
				ConfBlockUpdate confUpdate=(ConfBlockUpdate)confBlockService.getObject(ConfBlockUpdate.class, "key-black");
				if(confUpdate!=null){
					confUpdate.setUpdateTime(new Date());
					confBlockService.saveObject(confUpdate);				
				}
			}
			if(isDomainWhite){
				//域名、白名单过滤
				ConfBlockUpdate confUpdate=(ConfBlockUpdate)confBlockService.getObject(ConfBlockUpdate.class, "domain-white");
				if(confUpdate!=null){
					confUpdate.setUpdateTime(new Date());
					confBlockService.saveObject(confUpdate);				
				}
			}
			if(isDomainBlack){
				//域名、黑名单过滤
				ConfBlockUpdate confUpdate=(ConfBlockUpdate)confBlockService.getObject(ConfBlockUpdate.class, "domain-black");
				if(confUpdate!=null){
					confUpdate.setUpdateTime(new Date());
					confBlockService.saveObject(confUpdate);				
				}
			}
			
			this.setSuccessinfo(this.getText("black.white.import.success"));
		}catch(Exception e){
			e.printStackTrace();
			this.setErrorInfo(this.getText("file.import.failed"));
			return preImport();
		}
		
		return "list";
	}
	
	public String doExport()throws Exception{
		log.info("sortField="+sortField);
		log.info("sortMode="+sortMode);
		if(sortField!=null&&!sortField.trim().equals("")){
			orderByScript="order by "+sortField+" "+sortMode;
		}
		
		List<Object[]> result=confBlockService.queryBlackWhiteList(q_blocktype, q_blackorwhite, q_flag, q_value, orderByScript);
		
		log.info("result.size="+result.size());
		
		HttpServletResponse response = ServletActionContext.getResponse();
		//response.reset();
		
		response.setHeader("Content-Type","application/download; charset=utf-8");
		response.setHeader("Content-disposition","attachment;filename=BlackWhite.csv");
		
		
		for(Object[] data:result){
			String col1=data[0].toString().equals("1")?"key":"domain";
			String col2=data[1].toString().equals("1")?"white":"black";
			
			response.getWriter().print(col1+","+col2+","+data[2]+","+data[3]);
			response.getWriter().println();
		}
		
		response.getWriter().flush();
		response.flushBuffer();
		
		return null;
	}

	// actions end

	// getters and setters begin



	public ConfBlock getConfBlock() {
		return this.confBlock;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getQ_blackorwhite() {
		return q_blackorwhite;
	}

	public void setQ_blackorwhite(String q_blackorwhite) {
		this.q_blackorwhite = q_blackorwhite;
	}

	public String getQ_blockid() {
		return q_blockid;
	}

	public void setQ_blockid(String q_blockid) {
		this.q_blockid = q_blockid;
	}

	public String getQ_value() {
		return q_value;
	}

	public void setQ_value(String q_value) {
		this.q_value = q_value;
	}

	public void setIds(Integer[] ids) {
		this.ids = ids;
	}

	public void setConfBlock (ConfBlock confBlock) {
		this.confBlock = confBlock;
	}


	public void setConfBlockService(ConfBlockService confBlockService) {
		this.confBlockService = confBlockService;
	}
	
	
	public String getQ_blocktype() {
		return this.q_blocktype;
	}

	public void setQ_blocktype(String blocktype) {
		this.q_blocktype = blocktype;
	}
	public String getQ_flag() {
		return this.q_flag;
	}

	public void setQ_flag(String flag) {
		this.q_flag = flag;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	
	// getters and setters end
}